package pl.edu.agh.pros.android.listener;

import org.jivesoftware.smack.XMPPException;
import org.ros.node.ConnectedNode;
import org.ros.node.Node;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeListener;

import pl.edu.agh.pros.android.MainActivity;
import pl.edu.agh.pros.conf.ProxyConfiguration;
import pl.edu.agh.pros.connector.IServerConnector;
import pl.edu.agh.pros.connector.gae.GAEServerConnector;
import pl.edu.agh.pros.proxy.RosProxy;
import pl.edu.agh.pros.proxy.RosProxyHandler;
import android.util.Log;

public class UltimateNodeListener implements NodeListener {

	private static final String CLIENT_APP_KEY = "2001882d559f-4927-4d56-aece-e3cc0712fbff";
	private static final String TAG = "UltimateNodeListener";
	private final static IServerConnector serverConnector = new GAEServerConnector("http://rosproxy.appspot.com/"); //$NON-NLS-1$

	private static RosProxy rosProxy;
	private RosProxyHandler rosProxyHandler;
	private final String topic;
	private final String type;
	private final boolean isPublisher;
	private final NodeConfiguration nodeConfiguration;

	private static boolean initialized = false;

	public UltimateNodeListener(NodeConfiguration nodeConfiguration, String topic, String type, boolean isPublisher) {
		this.nodeConfiguration = nodeConfiguration;
		this.topic = topic;
		this.type = type;
		this.isPublisher = isPublisher;
	}

	@Override
	public void onStart(ConnectedNode node) {
		init(nodeConfiguration);
		ProxyConfiguration proxyConfiguration = new ProxyConfiguration(topic, type);
		if (isPublisher) {
			rosProxyHandler = rosProxy.createProxyForTopicPublisher(proxyConfiguration);
		} else {
			rosProxyHandler = rosProxy.createProxyForTopicSubscriber(proxyConfiguration);
		}
		rosProxyHandler.start();
		rosProxyHandler.awaitStart();
	}

	@Override
	public void onShutdown(Node node) {
		if (rosProxyHandler != null) {
			rosProxyHandler.stop();
		}
		if (rosProxy != null) {
			rosProxy.stop();
		}
	}

	@Override
	public void onShutdownComplete(Node node) {
		// do nothing
	}

	@Override
	public void onError(Node node, Throwable throwable) {
		if (rosProxyHandler != null) {
			rosProxyHandler.stop();
		}
		if (rosProxy != null) {
			rosProxy.stop();
		}
	}

	private static void init(NodeConfiguration nodeConfiguration) {
		if (initialized) {
			return;
		}
		synchronized (UltimateNodeListener.class) {
			if (initialized) {
				return;
			}
			try {
				rosProxy = RosProxy.newInstance(CLIENT_APP_KEY, MainActivity.deviceId, nodeConfiguration,
						serverConnector);
				rosProxy.start();
				rosProxy.awaitStart();
				initialized = true;
			} catch (XMPPException e) {
				Log.e(TAG, "Error initializing RosProxy", e);
			}
		}
	}

}
